<template>
  <div class="product-edit-form">
    <div class="fe-page-header" v-if="!justGuide">
      <div class="fe-page-header__left">
        {{ isEdit ? $t('common.pageTitle.pageProductEdit') : $t('common.pageTitle.pageCreateProduct') }}
      </div>
      <div class="fe-page-header__right">
        <FormCellChange class="mar-r-8" :count="formCellCount" @update="(e)=>{formCellCount=e}"></FormCellChange>
        <el-button type="plain-third" @click="back">
          {{ $t('common.base.cancel') }}
        </el-button>
        <el-button type="plain-third" @click="changeVisibleProp(true)">
          <i class="iconfont icon-file-copy font-12"></i>
          {{ $t('product.form.btns.btn2') }}
        </el-button>
        <el-button type="primary" @click="submit(false)" :loading="pending">
          {{ $t('common.base.save') }}
        </el-button>
        <el-button v-if="!productId && isQrcodeEnabled && canProductCodeCreate" type="primary" :loading="pending" @click="submit(true)" class="btn btn-primary ">
          {{ $t('product.form.btns.btn1') }}
        </el-button>
      </div>
    </div>
    <div class="form-builder-container" :class="[formCellCount > 1 ? 'form-builder-container-cell' : '']">
    <form-builder
      id="formId"
      ref="form"
      class="bbx-cell-form-builder"
      :fields="productFields"
      :value="value"
      :is-edit="isEdit"
      :form-cell-count="formCellCount"
      mode="product"
      @update="update"
      :formEditingMode="formEditingMode"
      @getDeleteFiles="getDeleteFiles"
    >
      <template slot="template" slot-scope="{ field }">
        <form-item :label="field.displayName" class="bbx-form-cell-item">
          <base-select
            v-model="value.template"
            :remote-method="searchTemplate"
            @input="updateTemplate"
          >
            <div
              class="product-template-option"
              slot="option"
              slot-scope="{ option }"
            >
              <h3>{{ option.name }}</h3>
              <p>
                <span
                ><label>{{ $t('product.form.productTemplate.serialNumber') }}：</label
                ><span>{{ option.serialNumber }}</span></span
                >
                <span
                ><label>{{ $t('product.form.productTemplate.type') }}：</label><span>{{ option.type }}</span></span
                >
              </p>
            </div>
          </base-select>
        </form-item>
      </template>
      <!-- 是否关联客户 -->
      <form-item :label="$t('product.associateCustomerOrNot')" class="customer-bind bbx-form-cell-item" v-if="hasBindCustomer">
        <el-radio-group class="customer-bind-radio-group" v-model="radioBind" @change="customerBind">
          <el-radio :label="1">{{$t('common.base.yes')}}</el-radio>
          <el-radio :label="0">{{$t('common.base.no')}}</el-radio>
        </el-radio-group>
        <i class="iconfont icon-fd-info tip"></i><span class="tip">{{ $t('product.form.tips.tip5') }}</span>
      </form-item>

      <template slot="catalogId" slot-scope="{ field }">
        <form-item :label="field.displayName" class="bbx-form-cell-item" :validation='validationCatalog'>
          <form-cascader :field='field' :tree='catalogTree' version='new' :value='catalog' :remote-search="true" @input='catalogInput' @beforeFilter="beforeFilter"></form-cascader>
        </form-item>
      </template>
      <template
        slot="customer"
        slot-scope="{ field }"
        v-if="!customerIsReadonly && showCustomer"
      >
        <form-item :label="field.displayName" class="bbx-form-cell-item" validation>
          <customer-select
            v-model="value.customer"
            :field="customerField"
            :remote-method="searchCustomer"
            :update-customer="updateCustomer"
            type="customer"
            @createInfo="createInfo"
            :placeholder="$t('common.placeholder.searchCustomer')"
          ></customer-select>
        </form-item>
        <form-item
          :label="$t('common.base.contact')"
          class="bbx-form-cell-item"
          :is-not-null="field.setting.customerOption.linkmanNotNull"
          v-if="
            field.setting.customerOption && field.setting.customerOption.linkman
          "
          :validation='validationLinkman'
        >
          <form-customer-select
            v-model="value.linkman"
            :field="getField('linkman', customerField)"
            :remote-method="searchCustomerLinkman"
            :update-linkman="updateLinkman"
            @createInfo="createInfo"
            type="linkman"
            :placeholder="$t('product.form.placeholder.customerCheck')"
          ></form-customer-select>
        </form-item>
        <!-- <span class="product_error" v-if="!validLinkman">请选择联系人</span> -->

        <form-item
          :label="$t('product.type.customerAddress')"
          class="bbx-form-cell-item"
          :is-not-null="field.setting.customerOption.addressNotNull"
          v-if="
            field.setting.customerOption && field.setting.customerOption.address
          "
          :validation='validationAddress'
        >
          <form-customer-select-address
            v-model="value.customerAddress"
            :field="getField('productAddress', customerField)"
            :remote-method="searchCustomerAddress"
            :update-customer-address="updateCustomerAddress"
            @createInfo="createInfo"
            type="address"
            :placeholder="$t('product.form.placeholder.customerCheck')"
          ></form-customer-select-address>
        </form-item>
      </template>

      <template slot="serialNumber" slot-scope="{ field }">
        <form-item :label="field.displayName" class="bbx-form-cell-item">
          <form-text
            :field="field"
            :value="value.serialNumber"
            @update="update"
            :placeholder="genPlaceholder(field)"
          />
        </form-item>
        <span class="product_error" v-if="serialNumberExist"
        >{{ $t('product.form.tips.tip6') }}</span
        >
      </template>

      <!-- start 产品类型 -->
      <template slot="type" slot-scope="{ field }">
        <form-item :label="field.displayName" class="bbx-form-cell-item">
          <div class="input-and-btn">
            <form-select
              :field="field"
              :source="
                field.setting.dataSource.map((d) => {
                  return {
                    text: d,
                    value: d,
                  };
                }) || []
              "
              v-model="value.type"
              :clearable="false"
              :placeholder="genPlaceholder(field)"
            />
          </div>
        </form-item>
      </template>
      <!-- end 产品类型 -->
    </form-builder>
    </div>
    
    <edit-contact-dialog
      ref="EditContactDialog"
      :customer="customer"
      @updateLinkman="updateLinkman"
    />
    <edit-address-dialog
      ref="EditAddressDialog"
      :customer-id="customerId"
      @updateCustomerAddress="updateCustomerAddress"
    />
    <clone-product-dialog
      ref="cloneProductDialog"
      :visible-prop="visibleProp"
      @changeVisibleProp="changeVisibleProp"
      @confirm="dialogConfirm"
    />
    <!-- 新建客户Start    -->
    <edit-customer-dialog
      ref="EditCustomerDialog"
      @updateCustomerRelation="updateCustomerRelation"
    />
    <!-- 新建客户Etart    -->
    <!-- :default-address="selectedAddress" -->
  </div>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import FormMixin from '@src/component/form/mixin/form';
import { fmt_address } from '@src/filter/fmt';
// import {searchCustomer} from '@src/api/EcSearchApi.js';
import {
  checkSerialNumber,
  getProductTemplateList,
  searchCustomerAddressForProduct,
} from '@src/api/ProductApi';
import { cloneData, queryCatalogTree } from "@src/api/ProductV2Api";
import { getCustomerList } from '@src/api/CustomerApi'
import _ from "lodash";
import { parse } from '@src/util/querystring';

import EditContactDialog from './EditContactDialog.vue';
import EditAddressDialog from './EditAddressDialog.vue';
import EditCustomerDialog from "./EditCustomerDialog.vue";
import CloneProductDialog from '@src/modules/product/components/CloneProductDialog.vue';
import {productSerachCustomer, productSearchTemplate} from '@src/modules/guideForNewUser/initData.js'
import { backToFromAccurateTab } from '@src/util/platform'

import { customerAddressSelectConversion } from '@src/util/conversionFunctionUtil.ts'
/* version control mixin */
import { VersionControlProductMixin } from '@src/mixins/versionControlMixin'
import { t as $t} from '@src/locales'
import { hasBSCEnterpriseEdition } from '@src/util/version'
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue'

export default {
  name: "product-edit-form",
  mixins: [VersionControlProductMixin],
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Object,
      required: true,
    },
    productId: {
      type: String,
      default: '',
    },
    customerIsReadonly: {
      type: Boolean,
      default: false,
    },
    justGuide: {
      type: Boolean,
      default: false,
    },
    pending:{
      type:Boolean,
      default:false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    hasReturn: {
      type: Boolean,
      default: true
    }
  },
  inject: ['initData', 'cloneProduct'],
  data() {
    return {
      validation: this.buildValidation(),
      template: [],
      serialNumberExist: false,
      visibleProp:false,
      catalog:[],
      catalogTree:[],
      radioBind:1,
      formCellCount:1,
      radioBind: 1,
      needServerDeleFiles: []
    };
  },
  watch: {
    'value': {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {
        if(!newValue.customer?.length && this.initData?.id){
          this.radioBind=0
          this.customerBind()
        }
      }
    }
  },
  mounted(){
    const existCatalog=this.fields.find(item=>item.fieldName==="catalogId");
    if(existCatalog) this.getTreeList();

    this.$nextTick(()=>{
      const { source } = parse(window.location.search) || {};
      if(source) {
        this.scrollToView();
      }
    })
  },
  computed: {
    productFields() {
      // 服务云企业版产品列表隐藏产品模版字段
      if(hasBSCEnterpriseEdition()) {
        return this.fields.filter(item=> item.fieldName != 'template')
      }
      return this.fields
    },
    // 启用产品超级二维码功能
    isQrcodeEnabled() {
      // 纯客服云版本不显示超级二维码
      return this.initData.productConfig.qrcodeEnabled && (this._isShowProductSuperQrcode || this._isShowProductQrcode)
    },
    auth () {
      return this.initData?.loginUser?.authorities || this.initData?.authorities
    },
    canProductCodeProduct() {
      return this.auth?.PRODUCT_CODE_PRODUCT
    },
    // 生成二维码的权限
    canProductCodeCreate() {
      return this.auth?.PRODUCT_CODE_CREATE
    },
    showCustomer(){
      return this.hasBindCustomer?this.radioBind:true
    },
    validLinkman(){
      return this.customerField.setting.customerOption.linkmanNotNull
    },
    customerField() {
      return this.fields.filter((f) => f.fieldName === 'customer')[0];
    },
    hasBindCustomer(){
      return this.initData?.productConfig?.productCreateUnBindCustomer
    },
    isPhoneUnique() {
      return this.initData.isPhoneUnique || false;
    },
    customer() {
      let customer = (this.value.customer && this.value.customer[0]) || {};
      if (!customer.id && customer.value) {
        customer.id = customer.value;
      }
      return customer || {};
    },
    customerId() {
      return (this.customer && (this.customer.id || this.customer.value)) || '';
    },
    formEditingMode() {
      return this.isEdit ? 'edit' : 'create'
    }
  },
  methods: {
    // 跳转到指定位置 - 从产品质保信息附加组件跳转过来定位到质保信息
    scrollToView(){
      setTimeout(() => {
        let index = this.fields.findIndex(val => {
          return val.fieldName == 'qualityInfo'
        })

        index && document.getElementById('formId').children[index].scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'start',
        });
      }, 500);
    },
    // 产品类型远程搜索
    beforeFilter: _.debounce(async function(value){
      if(!value) return this.getTreeList();
      try {
        const { code, message, result } = await queryCatalogTree({ keyWord: value });
        if (code === 0) {
          this.deleteEmpty(result);
          this.catalogTree = result;
          this.initCatalog();
        } else {
          this.$platform.notification({
            type: 'error',
            title: '请求错误',
            message: message
          })
        }
      } catch (err) {
        console.error(err);
      }
    }, 500),
    
    customerBind(){
      this.$emit('getBind',this.radioBind)
    },
    // 返回
    back(){
      let fromid = window.frameElement.getAttribute('fromid');
      if (!fromid || !this.isEdit) {
        const id = window.frameElement.dataset.id
        return this.$platform.closeTab(id)
      }
      let nowId = window.frameElement.getAttribute('id');
      backToFromAccurateTab(nowId)
    },
    validationLinkman(){
      if(this.customerField.setting.customerOption.linkmanNotNull){
       return new Promise((resolve, reject) => {
        if(!this.value.linkman.length) {
          return resolve(this.$t('product.form.validationTips.linkman'));
        } 
         resolve(null);
        })
      }
    },
     validationAddress(){
      if(this.customerField.setting.customerOption.addressNotNull){
       return new Promise((resolve, reject) => {
        if(!this.value.customerAddress.length) {
          return resolve(this.$t('product.form.validationTips.customerAddress'));
        } 
         resolve(null);
        })
      }
    },
    validationCatalog(){
      const catalogIdItem=this.fields.find(item=>item.fieldName==='catalogId');
      let isNull;
      if(catalogIdItem){
        isNull=!catalogIdItem.isNull;
      }
      return new Promise((resolve, reject) => {
        if(!this.catalog.length && isNull) {
          return resolve(this.$t('product.form.validationTips.catalogId'));
        } 
        resolve(null);
      })
    },
    catalogInput(value){
      const length = value.length;
      this.catalog = value;
      let selectLabel = {};
      if (length) {
        selectLabel = this.catalogTree.filter((item) => item.id === value[length - 1])[0]
      }

      const field = this.fields.find(item=>item.fieldName === 'catalogId');
      this.update({
        field,
        newValue:{
          label: selectLabel?.name || '',
          id: length ? value[length - 1] : '',
          fromType: 'inputEvent'
        }
      })
    },
    initCatalog(){
      const keys=Object.keys(this.value);
      const catalogKey=keys.find(key=>key==='catalogId');
      if(catalogKey){
        const catalogId=this.value[catalogKey];
        const id=Array.isArray(catalogId)?catalogId[0]?.id:catalogId.id;
        let treeArr=[];
        this.flat(this.catalogTree,treeArr);
        if(id) this.getCatalogParents(id,treeArr,this.catalog);
      }
    },
    // 拉平产品类型树
    flat(tasks,arr){
      tasks.forEach(item=>{
        arr.push(item);
        if(item.tasks && item.tasks.length){
          this.flat(item.tasks,arr);
        }
      });
    },
    // 获取产品类型id及其父级
    getCatalogParents(id,treeArr,catalogArr){
      catalogArr.unshift(id);
      // vip及标准版产品类型只有一层，所以取值时不取父类型，否则编辑时，对于原先多层的类型会匹配失败，导致类型没有显示
      if (this.initData.openSuperCodePro === false) return
      const item=treeArr.find(t=>t.id===id);
      if(item && item.parentId){
        this.getCatalogParents(item.parentId,treeArr,catalogArr);
      }
    },
    async getTreeList(){
      const productType = this.value?.catalogId;
      const catalogId = Array.isArray(productType) ? productType?.[0]?.id: productType?.id;
      try{
        const {code,message,result}=await cloneData({catalogId: catalogId || ''});
        if(code===0){
          this.deleteEmpty(result);
          this.catalogTree=result;
          this.initCatalog();
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list){
      list.forEach(item=>{
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    // submitChooseQrcode(){
    //   this.$emit('submitChooseQrcode');
    // },
    submit(createQrcode=false){
      this.$emit('submit',createQrcode);
    },
    getField(tag, field) {
      let tv = Object.assign({}, field);
      tv.fieldName = tag;
      tv.formType = 'extend';
      tv.displayName = tag == 'linkman' ? this.$t('common.base.contact') : this.$t('common.base.address');
      tv.isNull = tag == 'linkman'
        ? !tv.setting.customerOption.linkmanNotNull
        : !tv.setting.customerOption.addressNotNull;

      return tv;
    },
    updateTemplate(value) {
      let nv = null;
      const template = value[0];

      this.fields.forEach((f) => {
        const isUserForm = f.formType === 'user';
        const isNvEmpty = _.isEmpty(template?.attribute?.[f.fieldName]);
        // 人员控件如果设置了默认值，并且产品模版里面为空的话不赋值
        if(f.isSystem) {
          nv =  template[f.fieldName]
        } else {
          if(!(isUserForm && isNvEmpty)) {
            nv = template.attribute[f.fieldName];
          }
        }


        if (f.formType === 'address') {
          console.log(nv);
        }

        if (!!nv && f.fieldName != 'customer' && f.fieldName != 'template') {
          if (f.fieldName === 'catalogId') nv = { id: nv }

          this.update({
            field: f,
            newValue: nv,
          });
        }
      });
    },
    buildValidation() {
      if(this.justGuide || !this.radioBind) return 
      const serialNumberUnique = this.initData.productConfig.serialNumberUnique;

      let checkSerialNumberFn = _.debounce(function(
        params,
        resolve,
        changeStatus
      ) {
        if (!params.serialNumber) return resolve(null);

        changeStatus(true);
        return checkSerialNumber(params)
          .then((res) => {
            changeStatus(false);
            return resolve(res.error ? res.error : null);
          })
          .catch((err) => console.error(err));
      },
      500);

      const that = this;

      return Object.freeze({
        serialNumber: !serialNumberUnique
          ? true
          : function(value, field, changeStatus) {
            let params = {
              id: that.productId || '',
              serialNumber: value,
            };

            return new Promise((resolve, reject) =>
              checkSerialNumberFn(params, resolve, changeStatus)
            );
          },
      });
    },

    genPlaceholder(field) {
      return FormUtil.genPlaceholder(field);
    },

    update({ field, newValue, oldValue, fromType }) {
      let { fieldName, displayName } = field;
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      if (fieldName === 'serialNumber') {
        if (newValue && !this.justGuide) {

          checkSerialNumber(
            { id: this.productId, serialNumber: newValue },
            false
          ).then((res) => {
            if (res.hasOwnProperty('ok')) {
              this.serialNumberExist = false;
            } else {
              this.serialNumberExist = true;
            }
          });
        } else {
          this.serialNumberExist = false;
        }
      } else if(fieldName === 'catalogId' && this.catalogTree && fromType !== 'inputEvent') {
        this.catalog = this.searchCatalogIds(this.catalogTree, newValue.id) || []
      }
      let value = this.value;

      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },
    // 在产品类型选项中查找对应的值
    searchCatalogIds (catalogOption, catalogId) {
      for(let catalog of catalogOption) {
        if(catalog.tasks) {
          // 递归寻找值
          let res = this.searchCatalogIds(catalog.tasks, catalogId)
          // 子级找到值，就把这级的id加进去
          if (res) {
            res.unshift(catalog.id)
            return res
          }
        } else if (catalog.id === catalogId) {
          // 找到值并返回
          return [catalogId]
        }
      }
    },
    updateCustomer(value) {
      const cf = this.fields.filter((f) => f.fieldName === 'customer')[0];
      this.update({
        field: cf,
        newValue: value,
      });
      this.fetchCustomer(value);
    },
    updateLinkman(value) {
      let field = {
        fieldName: 'linkman',
        displayName: this.$t('common.base.contact'),
      };
      this.update({
        field,
        newValue: value,
      });
      this.fetchLinkmanAddress(value);
    },
    updateCustomerAddress(value) {
      let field = {
        fieldName: 'customerAddress',
        displayName: this.$t('common.base.address'),
      };
      this.update({
        field,
        newValue: value,
      });
    },
    updateCustomerRelation(data) {
      // 绑定客户
      const cf = this.fields.filter((f) => f.fieldName === 'customer')[0];
      this.update({
        field: cf,
        newValue: [{ label: data.name,  value: data.id, id: data.id}]
      });

      // 绑定联系人
      this.update({
        field: { fieldName: 'linkman', displayName: '联系人'},
        newValue: [{ value: data.lmId, label: data.lmName, phone: data.lmPhone}],
      });

      // 绑定地址
      let value = []
      if(data.addressId) {
        value = [customerAddressSelectConversion({
          id: data.addressId,
          country: data.country,
          province: data.province,
          city: data.city,
          dist: data.dist,
          address: data.address,
          latitude: data.latitude,
          longitude: data.longitude,
        })]
      }
      this.update({
        field: { fieldName: 'customerAddress', displayName: '地址'},
        newValue: value,
      });
      this.$refs.EditCustomerDialog.addCustomerDialog = false;
    },

    clearLinkman() {
      let field = {
        fieldName: 'linkman',
        displayName: this.$t('common.base.contact'),
      };
      this.update({
        field,
        newValue: [],
      });
    },
    clearCustomerAddress() {
      let field = {
        fieldName: 'customerAddress',
        displayName: this.$t('common.base.address'),
      };
      this.update({
        field,
        newValue: [],
      });
    },
    validate() {
      return this.$refs.form
        .validate(false)
        .then((valid) => {
          return valid;
        })
        .catch((err) => console.error(err));
    },
    searchCustomer(params) {
      // params has three properties include keyword、pageSize、pageNum.

      if(this.justGuide) return Promise.resolve(productSerachCustomer)
      const pms = params || {};

      return getCustomerList({
        ...pms,
        status: 1
      })
        .then((res) => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map((customer) =>
              Object.freeze({
                id: customer.id,
                label: customer.name,
                value: customer.id,
                lmPhone: customer.lmPhone,
                lmName: customer.lmName,
                serialNumber: customer.serialNumber,
                customerAddress: customer.customerAddress,
              })
            );
          }
          return res;
        })
        .catch((e) => console.error(e));
    },
    fetchCustomer(params) {
      const pms = {
        customerId: params[0].id,
        notNull: true,
        productId: '',
      };

      this.clearLinkman();
      this.clearCustomerAddress();
      return this.$http
        .get('/task/defaultInfo', pms)
        .then((res) => {
          if (!res) return;
          let linkman = [
            {
              label: `${res.linkman.name || ''} ${res.linkman.phone || ''}`,
              value: res.linkman.id,
              phone: res.linkman.phone,
            },
          ];
          this.updateLinkman(linkman);

          let address = [
            {
              label:
                res.address
                && fmt_address(res.address),
              value: res.address && res.address.id,
            },
          ];
          res.address ? this.updateCustomerAddress(address) : '';

          return res;
        })
        .catch((e) => console.error(e));
    },
    fetchLinkmanAddress(value) {
      let linkman = value[0];
      if (!linkman) return;
      const pms = {
        lmId: linkman.value,
      };
      this.clearCustomerAddress();
      return this.$http
        .get('/task/getLmBindAddress', pms)
        .then((res) => {
          if (!res) return;
          let address = [
            {
              label:
                res.data
                && fmt_address(res.data),
              value: res.data && res.data.id,
            },
          ];
          res.data && res.data.id ? this.updateCustomerAddress(address) : '';
          return res;
        })
        .catch((e) => console.error(e));
    },
    searchTemplate(params) {
      // params has three properties include keyword、pageSize、pageNum.
      if(this.justGuide) return Promise.resolve(productSearchTemplate)
      const pms = params || {};

      return getProductTemplateList(pms)
        .then((res) => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map((template) =>
              Object.freeze({
                label: template.name,
                value: template.id,
                ...template,
              })
            );
          }
          return res;
        })
        .catch((e) => console.error(e));
    },
    searchCustomerLinkman(params) {
      if (!this.value.customer.length) {
        return new Promise((resolve, reject) => {
          resolve(null);
        });
      }

      const pms = params || {};
      let customer = this.value.customer[0];
      pms.customerId = customer.value;

      return this.$http
        .get('/customer/linkman/list', pms)
        .then((res) => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map((linkman) =>
              Object.freeze({
                label: `${linkman.name || ''} ${linkman.phone || ''}`,
                value: linkman.id,
                phone: linkman.phone,
              })
            );
          }

          return res;
        })
        .catch((e) => console.error(e));
    },
    searchCustomerAddress(params) {
      if (!this.value.customer.length) {
        return new Promise((resolve, reject) => {
          resolve(null);
        });
      }

      const pms = params || {};
      let customer = this.value.customer[0];
      let linkman = this.value.linkman[0];
      pms.customerId = customer.value;
      // pms.linkmanId = linkman.value;

      return searchCustomerAddressForProduct(pms)
        .then((res) => {
          if (!res || !res.data) return;
          if (res.data.list) {
            res.data.list = res.data.list.map((address) =>
              Object.freeze({
                label: fmt_address(address.showAddress ? address.showAddress : address ),
                value: address.id,
              })
            );
          }

          return res.data;
        })
        .catch((e) => console.error(e));
    },
    createInfo(type) {
      if (!this.value.customer.length && type !== 'customer') {
        this.$platform.alert(this.$t('product.form.tips.tip7'));
        return;
      }
      if (type == 'linkman') this.$refs.EditContactDialog.openDialog();
      if (type == 'address') this.$refs.EditAddressDialog.openDialog();
      if (type === 'customer') this.$refs.EditCustomerDialog.openDialog();
    },
    changeVisibleProp(e) {
      this.visibleProp = e;
    },
    dialogConfirm(e){
      if(e){
        console.log(e, 'dialogConfirm')
        this.cloneProduct(e.nowChooseData)
        this.changeVisibleProp(false)
      }
    },
    // 删除附件
    getDeleteFiles(files) {
      this.needServerDeleFiles = [...this.needServerDeleFiles, ...files]
    }
  },
  components: {
    [EditContactDialog.name]: EditContactDialog,
    [EditAddressDialog.name]: EditAddressDialog,
    CloneProductDialog,
    [EditCustomerDialog.name]: EditCustomerDialog,
    'customer-select': {
      name: 'customer-select',
      mixins: [FormMixin],
      inject: ['initData'],
      props: {
        value: {
          type: Array,
          default: () => [],
        },
        field: {
          type: Object,
          default: () => ({}),
        },
        remoteMethod: Function,
        updateCustomer: Function,
        placeholder: String,
        type: String,
      },
      computed: {
        auth() {
          return (
              this.initData?.loginUser?.authorities || this.initData?.authorities
          );
        },
        createdPermission() {
          return this.auth.CUSTOMER_CREATE === 3;
        },
      },
      methods: {
        input(value) {
          this.$emit('input', value);
        },
        createInfo(type) {
          this.$emit('createInfo', type);
        },
        renderBtn() {
          if (!this.createdPermission) return null;
          return (
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              onClick={(e) => this.createInfo(this.type, e)}
              class="action-btn margin-left-10"
              >
                {$t('common.base.create')}
            </el-button>
          );
        },
      },

      render(h) {
        return (
          <div class="form-customer-select">
            <biz-remote-select
              key={JSON.stringify(this.value)}
              value={this.value}
              field={this.field}
              remoteMethod={this.remoteMethod}
              onInput={this.updateCustomer}
              placeholder={this.placeholder}
              computedWidthKeys={['name']}
              {...{
                scopedSlots: {
                  option: (props) => {
                    return (
                      <div class="customer-template-option" slot="option" slot-scope="{ option }">
                        <h3>{ props.option.label }</h3>
                        <p>
                          <span>
                            <label>{this.$t('common.base.phone')}：</label>
                            <span>{ props.option.lmPhone }</span>
                          </span>
                          <span>
                            <label>{this.$t('common.base.serialNumber')}：</label>
                            <span>{ props.option.serialNumber }</span>
                          </span>
                          {
                            props.option && props.option.customerAddress
                              ? <span>
                                <label>{this.$t('common.base.customerAddress')}：</label>
                                <span>
                                  { fmt_address(props.option.customerAddress) }
                                </span>
                              </span>
                              : null
                          }
                        </p>
                      </div>
                    );
                  },
                },
              }}
            />
            {this.renderBtn(h)}
          </div>
        );
      },
    },

    'form-customer-select': {
      name: 'form-customer-select',
      mixins: [FormMixin],
      inject: ['initData'],
      props: {
        value: {
          type: Array,
          default: () => [],
        },
        field: {
          type: Object,
          default: () => ({}),
        },
        remoteMethod: Function,
        updateLinkman: Function,
        placeholder: String,
        type: String,
      },
      computed: {
        auth() {
          return (
            this.initData?.loginUser?.authorities || this.initData?.authorities
          );
        },
        createdPermission() {
          return this.auth.CUSTOMER_CREATE == 3;
        },
      },
      methods: {
        input(value) {
          this.$emit('input', value);
        },

        createInfo(type, event) {
          this.$emit('createInfo', type);
        },

        renderBtn() {
          if (!this.createdPermission) return null;
          return (
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              onClick={(e) => this.createInfo(this.type, e)}
              class="action-btn margin-left-10"
            >
              { this.$t('common.base.create') }
            </el-button>
          );
        },
      },
      render(h) {
        return (
          <div class="form-customer-select">
            <biz-remote-select
              key={JSON.stringify(this.value)}
              value={this.value}
              field={this.field}
              placeholder={this.placeholder}
              remoteMethod={this.remoteMethod}
              onInput={this.updateLinkman}
              clearable
              {...{
                scopedSlots: {
                  option: (props) => {
                    return (
                      <p class="customer-template-option customer-linkman task-ptb5">
                        <p>{ props.option.label }</p>
                      </p>
                    );
                  },
                },
              }}
            />
            {this.renderBtn(h)}
          </div>
        );
      },
    },

    'form-customer-select-address': {
      name: 'form-customer-select-address',
      mixins: [FormMixin],
      inject: ['initData'],
      props: {
        value: {
          type: Array,
          default: () => [],
        },
        remoteMethod: Function,
        updateCustomerAddress: Function,
        placeholder: String,
        type: String,
      },
      computed: {
        auth() {
          return (
            this.initData?.loginUser?.authorities || this.initData?.authorities
          );
        },

        createdPermission() {
          return this.auth.CUSTOMER_CREATE == 3;
        },
      },
      methods: {
        input(value) {
          this.$emit('input', value);
        },

        createInfo(type, event) {
          this.$emit('createInfo', type);
        },

        renderBtn() {
          if (!this.createdPermission) return null;
          return (
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              onClick={(e) => this.createInfo(this.type, e)}
              class="action-btn margin-left-10"
            >
              {this.$t('common.base.create')}
            </el-button>
          );
        },
      },
      render(h) {
        return (
          <div class="form-customer-select">
            <base-select
              value={this.value}
              placeholder={this.placeholder}
              remoteMethod={this.remoteMethod}
              onInput={this.updateCustomerAddress}
              clearable
            />
            {this.renderBtn(h)}
          </div>
        );
      },
    },
    FormCellChange,
  },
};
</script>

<style lang="scss">
.margin-left-10 {
  margin-left: 10px;
}
.product-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;

    & > span {
      width: 50%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;    

      & > label {
        padding: 0;
        width: 70px;
      }
      & > span {
        @include text-ellipsis();
      }
    }
  }
}

// .form-item-control {
//   .form-customer-select {
//     display: flex;

//     .base-select-container {
//       flex: 1;
//     }

//     .btn {
//       width: 60px;
//       height: 32px;
//       line-height: 22px;
//     }
//   }
// }

.base-modal-body {
  .form-builder {
    width: 540px;
  }
}
.customer-item {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 600;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;
    flex-wrap: wrap;
    flex-flow: column;

    & > span {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        padding: 0;
        width: 60px;
      }
      & > span {
        @include text-ellipsis();
      } 
    }
  }
}

// .customer-item {
//   h3 {
//     font-size: 14px;
//     margin: 0;
//     padding-left: 10px;
//   }

//   p {
//     display: flex;
//     margin: 0;
//     span {
//       label {
//         display: inline-block;
//         width: auto;
//       }

//       span {
//         margin-right: 10px;
//       }
//     }
//   }
// }

.customer-linkman {
  display: flex;
  margin: 0;

  span {
    label {
      display: inline-block;
      width: auto;
    }

    span {
      margin-right: 10px;
    }
  }
}
</style>

<style lang="scss" scoped>

.customer-bind{
  ::v-deep .form-item-control{
    display: flex;
    align-items: center;
    margin-bottom: 13px;
  }

  .customer-bind-radio-group{
   display: flex;
   label{
     padding-left: 0;
     width:60px;
   }
  }   
}
.tip{
    font-size:12px;
    color:#8c8c8c;
    margin-top:4px ;
  }

@mixin title-class {
  height: 48px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-weight: 600;
}
.normal-title-1 {
  @include title-class();
  padding: 12px 10px;
  height: auto;
  font-size: 20px;
  border-bottom: 1px solid #f4f7f5;
}
.normal-title-2 {
  @include title-class();
  padding: 0 12px;
  font-size: 16px;
}
.normal-title-2-bord-bottom {
  @extend .normal-title-2;
  border-bottom: 1px solid $color-border-l1;
  margin-bottom: 20px;
}
.product_error {
  color: #f56c6c;
  display: inline-block;
  transform: translateY(-8px);
  font-size: 12px;
}
</style>

<style lang="scss">
.in-frame-modal-view {
  
  height: 100%;
  overflow: hidden;
  
  .product-edit-form,
  .base-form {
    position: relative;
    height: 100%;
  }
  
  .normal-title-1 {
    position: fixed;
    right: 10px;
    bottom: 0px;
    width: calc(100% - 20px);
    background: #fff;
    
    display: flex;
    justify-content: flex-end;
    
    .flex-1 {
      flex: none;
      margin-right: 16px;
    }
    
  }
  
  .form-builder {
    height: calc(100vh - 70px);
    overflow-y: scroll;
    width: 100%;
    padding: 0 20px;
    margin-top: 0;
    padding-top: 16px;
  }
  
  .form-quality-info {
    margin-bottom: 30px;
  }
  
  .form-quality-info .form-builder {
    height: auto;
  }
  
  .product-edit-form > .form-builder {
    
    max-width: 100%;
    
  }
  
  .fe-page-header {
    
    top: inherit;
    
    .fe-page-header__left {
      display: none;
    }
    
  }
  
}
.customer-template-option {
  word-wrap: break-word;
  white-space: normal;
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }
  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;
    flex-wrap: wrap;
    flex-flow: column;
    & > span {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      flex: 1;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        padding: 0;
      }
    }
  }
}
</style>
<style lang="scss">
.form-item-control .form-customer-select {
  --input-btn-max-width: 77px;
  --input-btn-margin-left: 10px;
  --input-right: 10px;
  --input-icon-width: 25px;
  --input-icon-right: calc(var(--input-btn-max-width) + var(--input-right));
  --input-padd-right: calc(var(--input-icon-right) + var(--input-icon-width));
  --input-tag-right: var(--input-padd-right);
  display: block;
  position: relative;
  button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    max-width: var(--input-btn-max-width);
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    right: var(--input-right);
  }
  .base-select-container {
    .base-select-main-content {
      padding-right: calc(var(--input-padd-right) - var(--input-icon-width));
    }
    .content .clear-btn {
      padding-right: var(--input-icon-right);
    }
  }
  // 测试环境中的select组件的样式
  .biz-form-remote-select {
    .el-select .el-input {
      input {
        padding-right: calc(var(--input-padd-right) - var(--input-icon-width));
      }
      // icon用不到就消失掉它，记住padding-right要删除icon宽度，如上所示
      // .el-input__suffix {
      //   right:  var(--input-icon-right);
      // }
    }
  }
}
</style>